"""
response配置
"""

from dataclasses import dataclass
from flask import Response, abort, json
from flask_restful.reqparse import Argument


@dataclass
class RESCODE:
    """返回code"""

    OK = 200
    TOKEN_VERIFY_FAIL = 401
    PARAMS_FAIL = 1001
    USER_REPEAT = 1002
    REG_FAIL = 1003
    LOGIN_FAIL = 1004
    DB_FAIL = 1005


ERR_MAP = {
    RESCODE.OK: "成功",
    RESCODE.TOKEN_VERIFY_FAIL: "身份认证失效",
    RESCODE.PARAMS_FAIL: "参数校验失败",
    RESCODE.USER_REPEAT: "用户已被注册",
    RESCODE.REG_FAIL: "注册失败",
    RESCODE.LOGIN_FAIL: "登录失败",
    RESCODE.DB_FAIL: "数据库异常",
}


class ValidationArgs(Argument):
    """
    重写覆盖flask_restful参数校验返回格式
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def handle_validation_error(self, error, bundle_errors):
        # 校验失败信息，默认"参数校验失败"
        error_msg = (
            self.help.format(error_msg=str(error))
            if self.help
            else str(ERR_MAP.get(RESCODE.PARAMS_FAIL))
        )

        if bundle_errors:
            return error, {self.name: error_msg}

        error_body = {
            "code": RESCODE.PARAMS_FAIL,
            "message": f"{error_msg}" or ERR_MAP.get(RESCODE.PARAMS_FAIL),
            "success": False,
            "data": None,
        }

        return abort(Response(json.dumps(error_body)))


def res(code=200, data=None, message=""):
    """返回信息处理"""

    code_value = ERR_MAP.setdefault(code, None)
    message = (
        message
        if message
        else ("未知错误" if not code_value else ERR_MAP.get(code))
    )

    return {
        "code": code,
        "success": code == 200,
        "message": message,
        "data": data,
    }
